//
//  LLUIImageView.m
//  PandaMakeUp
//
//  Created by dl on 15/10/21.
//  Copyright © 2015年 lrlz. All rights reserved.
//

#import "LLUIImageView.h"
#import <SDWebImage/UIImageView+WebCache.h>

void LLImageCacheConfig(void) {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        //设置图片缓存最大内存
        [[SDImageCache sharedImageCache] setMaxMemoryCost:1024 * 1024 * 10];
        [[SDImageCache sharedImageCache] setMaxCacheAge:3600 * 24 * 7];
    });
}

void LLImageCacheClearMemory(void) {
    [[SDImageCache sharedImageCache] clearMemory];
}

NSString *LLImageUrlStrScaledWithSize(NSString *originUrl, int size) {
    NSString *retImageUrl = originUrl;
    if (![originUrl isKindOfClass:[NSString class]]) {
        return nil;
    }
    NSString *lowerCaseUrl = [originUrl lowercaseString];
    if ([lowerCaseUrl rangeOfString:@"alicdn"].location != NSNotFound) {
        retImageUrl = [NSString stringWithFormat:@"%@_%dx%d.jpg", originUrl, size, size];
    } else if ([lowerCaseUrl rangeOfString:@"alimmdn"].location != NSNotFound) {
        retImageUrl = [NSString stringWithFormat:@"%@@%dw_%dh_100Q.jpg", originUrl, size, size];
    }
    return retImageUrl;
}

void LLImageCacheClearWithCompletion(dispatch_block_t completion) {
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:completion];
    [[SDImageCache sharedImageCache] clearMemory];
}

void LLImageCachePreloadImages(NSArray *urls) {
    [urls enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

        if (![[SDWebImageManager sharedManager] cachedImageExistsForURL:obj]) {

            [[SDWebImageManager sharedManager] downloadImageWithURL:obj
                                                            options:SDWebImageRetryFailed | SDWebImageContinueInBackground
                                                           progress:NULL
                                                          completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
//                                                              DLog(@"Preload %@ OK!", imageURL);
                                                          }];
        }
    }];
}

void LLImageLoadImage(NSURL *url, void(^completion)(UIImage *)) {
    [[SDWebImageManager sharedManager] downloadImageWithURL:url options:SDWebImageRetryFailed | SDWebImageContinueInBackground progress:NULL completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        completion(image);
    }];
}

@interface LLUIImageView ()
@property(nonatomic, strong) CAGradientLayer *bottomGradientLayer;
@property(nonatomic, strong, readwrite) NSURL *imageURL;
@end

static UIColor *defaultBgColor = nil;

@implementation LLUIImageView

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setUp];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setUp];
    }
    return self;
}

- (void)setUp {
    if (defaultBgColor == nil) {
        defaultBgColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"pic_placeholder"]];
    }
    self.placeholderImage = nil;
    self.shouldShowIndicator = YES;
    self.cacheOptions = (SDWebImageRetryFailed | SDWebImageContinueInBackground | SDWebImageAvoidAutoSetImage);
    self.shouldShowIndicator = YES;
}

- (void)layoutSubviews {
    if (_showBottomGradientLayer && _bottomGradientLayer && self.ll_height > SUIT_H(40) + _bottomGradientLayerOffset) {
        _bottomGradientLayer.frame = CGRectMake(0, self.ll_height - SUIT_H(40) - _bottomGradientLayerOffset, self.ll_width, SUIT_H(40));
    }
    if (_shouldShowIndicator && _indicatorView) {
        _indicatorView.center = self.center;
    }
}

- (void)setClickBlock:(ClickEventBlock)clickBlock {
    _clickBlock = [clickBlock copy];
    if (clickBlock) {
        self.userInteractionEnabled = YES;
        [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click)]];
    }
}

- (UIActivityIndicatorView *)indicatorView {
    if (!_indicatorView) {
        _indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _indicatorView.hidesWhenStopped = YES;
        [self addSubview:_indicatorView];
    }
    return _indicatorView;
}

- (void)setImageUrlStr:(NSString *)url {
    [self setImageUrlStr:url touchBlock:self.clickBlock];
}

- (void)setImageUrlStr:(NSString *)url size:(int)size {
    [self setImageUrlStr:url size:size touchBlock:self.clickBlock];
}

- (void)setImageUrlStr:(NSString *)url touchBlock:(ClickEventBlock)block {
    [self setImageUrlStr:url size:IMAGE_SIZE_ORIGIN touchBlock:block];
}

- (void)setImageUrlStr:(NSString *)url size:(int)size touchBlock:(ClickEventBlock)block {
    if (_clickBlock != block) {
        self.clickBlock = block;
    }
    if (url && [url isKindOfClass:[NSString class]] && ![url isEqualToString:self.imageURL.absoluteString]) {
        self.backgroundColor = defaultBgColor;
        if (size > 0) {
            url = LLImageUrlStrScaledWithSize(url, size);
        }
        _imageURL = [NSURL URLWithString:url];

        if (self.shouldShowIndicator) {
            [self.indicatorView startAnimating];
        }

        @weakify(self)
        [self sd_setImageWithURL:_imageURL placeholderImage:self.placeholderImage options:self.cacheOptions progress:^(NSInteger receivedSize, NSInteger expectedSize) {

        }              completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            @strongify(self)
            self.layer.opacity = 0.5f;
            [UIView animateWithDuration:0.5f animations:^{
                self.layer.opacity = 1.f;
            }];
            self.backgroundColor = [UIColor clearColor];
            self.image = image;
            if (self.shouldShowIndicator) {
                [self.indicatorView stopAnimating];
                [self.indicatorView removeFromSuperview];
            }
        }];
    } else if (!url || [url isNullStr]) {
        self.image = self.placeholderImage;
    }
}

- (void)setShowBottomGradientLayer:(BOOL)showBottomGradientLayer {
    if (_showBottomGradientLayer != showBottomGradientLayer) {
        _showBottomGradientLayer = showBottomGradientLayer;
        if (!showBottomGradientLayer && _bottomGradientLayer) {
            [_bottomGradientLayer removeFromSuperlayer];
        }
        if (showBottomGradientLayer) {
            if (!_bottomGradientLayer) {
                _bottomGradientLayer = [CAGradientLayer layer];
                _bottomGradientLayer.opacity = 0.08f;
                _bottomGradientLayer.colors = @[(id) [UIColor whiteColor].CGColor, (id) [UIColor blackColor].CGColor];
                [self.layer addSublayer:_bottomGradientLayer];
            }
        }
    }
}

- (void)click {
    if (_clickBlock) {
        _clickBlock();
    }
}

@end
